from django.db.models import Q
from django.shortcuts import render
from django.views import View
import json
from iHome.utils.views import LoginJsonRequiredMixin
from .models import Order
import datetime
from apps.houses.models import House
from django import http
from django.db import transaction


# Create your views here.
class CommentView(LoginJsonRequiredMixin, View):
    def put(self, request, order_id):
        # 评价
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')
        with transaction.atomic():
            try:
                save_id = transaction.savepoint()
                order = Order.objects.get(id=order_id)
                order.comment = comment
                order.status = Order.ORDER_STATUS['COMPLETE']
                house = order.house
                house.order_count += 1
                house.save()
                order.save()
            except:
                transaction.savepoint_rollback(save_id)
                return http.JsonResponse({'errno': 4004, 'errmsg': '评论失败'})
        return http.JsonResponse({'errno': 0, 'errmsg': '评论成功'})


class OrderStatusView(LoginJsonRequiredMixin, View):
    def put(self, request, order_id):
        # 接单
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')
        if action == 'accept':
            order = Order.objects.filter(id=order_id).update(status=Order.ORDER_STATUS['WAIT_COMMENT'])

        elif action == 'reject':
            order = Order.objects.filter(id=order_id).update(status=Order.ORDER_STATUS['REJECTED'], comment=reason)
        return http.JsonResponse({'errno': 0, 'errmsg': '操作成功'})


class AddOrderView(LoginJsonRequiredMixin, View):
    def get(self, request):
        # 获取订单信息
        custom = request.GET.get('role')
        if custom == 'custom':
            order = Order.objects.filter(user=request.user)
        else:
            user = request.user
            houses = user.houses.all()
            order = []
            for house in houses:
                orders = house.order_set.all()
                for order_model in orders:
                    order.append(order_model)
        # user = request.user
        orders = []
        for i in order:
            orders.append({
                "amount": i.amount,
                "comment": i.comment,
                "ctime": i.create_time,
                "days": i.days,
                "end_date": i.end_date,
                "img_url": str(i.house.index_image_url),
                "order_id": i.id,
                "start_date": i.begin_date,
                "status": i.ORDER_STATUS_ENUM[i.status],
                "title": i.house.title
            })
        data = {'orders': orders}
        return http.JsonResponse({'errno': 0, 'errmsg': 'ok', 'data': data})

    def post(self, request):
        # 添加订单
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')
        try:
            house = House.objects.get(id=house_id)
        except:
            return http.JsonResponse({'errno': 4001, 'errmsg': '房源不存在'})
        dayA = datetime.datetime.strptime(start_date, '%Y-%m-%d')
        dayB = datetime.datetime.strptime(end_date, '%Y-%m-%d')
        sub_day = dayB - dayA
        day = sub_day.days
        if day < house.min_days:
            return http.JsonResponse({'errno': 4501, 'errmsg': '小于最少可预订天数'})
        orders = Order.objects.filter(Q(house_id=house_id) & Q(begin_date__range=[dayA, dayB]) | Q(
            end_date__range=[dayA, dayB]))  # 这是查询该房屋目前的订单
        if orders:
            return http.JsonResponse({'errno': 4001, 'errmsg': '预订失败'})
        order = Order.objects.create(
            user=request.user,
            house=house,
            begin_date=start_date,
            end_date=end_date,
            days=day,
            house_price=house.price,
            amount=day * house.price,
            status=Order.ORDER_STATUS["WAIT_ACCEPT"]
        )
        data = {'order_id': order.id}
        return http.JsonResponse({'errno': 0, 'errmsg': '下单成功', 'data': data})
